// my-fresh-blog/routes/admin/login.tsx
import { h, Fragment } from "preact";
import { Head } from "$fresh/runtime.ts";
import { Handlers, PageProps } from "$fresh/server.ts";
import HeadComponent from "../../components/Head.tsx";
import { checkIsAdmin } from "../../utils/auth.ts";

interface LoginPageProps {
  error?: string;
  redirect?: string;
}

export const handler: Handlers<LoginPageProps> = {
  async GET(req, ctx) {
    if (await checkIsAdmin(req)) {
      const headers = new Headers(); headers.set("location", "/");
      return new Response(null, { status: 303, headers });
    }
    const url = new URL(req.url);
    const error = url.searchParams.get("error") || undefined;
    const redirect = url.searchParams.get("redirect") || "/";
    return ctx.render({ error, redirect });
  },
};

export default function AdminLoginPage({ data }: PageProps<LoginPageProps>) {
  const { error, redirect } = data || {};

  return (
    <>
      <HeadComponent title="管理员登录" description="管理员登录页面">
        <link rel="stylesheet" href="/styles.css" />
        <link rel="stylesheet" href="/article-styles.css" />
        <style>{`
          html, body {
            height: 100%;
            margin: 0;
            overflow: hidden;
          }
          
          /* 全屏毛玻璃背景 */
          .login-bg-overlay {
            position: fixed;
            inset: 0;
            background-color: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            z-index: 0;
          }
          
          /* 主容器 */
          .login-container {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            position: relative;
            z-index: 1;
          }
          
          /* 登录卡片 */
          .login-card {
            width: 100%;
            max-width: 400px;
            padding: 2.5rem;
            border-radius: 1rem;
            box-shadow: 
              0 8px 20px rgba(0, 0, 0, 0.1),
              0 0 15px rgba(200, 200, 255, 0.15),
              0 0 25px rgba(200, 200, 255, 0.1);
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border: 1.5px solid rgba(255, 255, 255, 0.3);
            animation: fadeIn 0.8s ease-out;
          }
          
          @keyframes fadeIn {
            from {
              opacity: 0;
              transform: translateY(20px);
            }
            to {
              opacity: 1;
              transform: translateY(0);
            }
          }
          
          /* 标题样式 */
          .login-title {
            font-size: 1.75rem;
            font-weight: 700;
            color: #3d3d3d;
            margin-bottom: 0.5rem;
            text-align: center;
          }
          
          .login-subtitle {
            font-size: 0.875rem;
            color: #666;
            margin-bottom: 2rem;
            text-align: center;
          }
          
          /* 表单样式 */
          .form-group {
            margin-bottom: 1.5rem;
          }
          
          .form-label {
            display: block;
            font-size: 0.875rem;
            font-weight: 500;
            color: #4a5568;
            margin-bottom: 0.5rem;
          }
          
          .form-input {
            width: 100%;
            padding: 0.75rem 1rem;
            font-size: 1rem;
            border: 1px solid rgba(255, 255, 255, 0.3);
            background: rgba(255, 255, 255, 0.25);
            color: #333;
            border-radius: 0.5rem;
            transition: all 0.3s ease;
          }
          
          .form-input:focus {
            outline: none;
            border-color: rgba(123, 94, 77, 0.5);
            box-shadow: 0 0 0 3px rgba(123, 94, 77, 0.2);
            background: rgba(255, 255, 255, 0.35);
          }
          
          .form-input::placeholder {
            color: #999;
          }
          
          /* 按钮样式 */
          .submit-button {
            display: block;
            width: 100%;
            padding: 0.875rem;
            background: #7b5e4d;
            color: white;
            border: none;
            border-radius: 0.5rem;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 2rem;
          }
          
          .submit-button:hover {
            background: #6a5040;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(106, 80, 64, 0.25);
          }
          
          .submit-button:active {
            transform: translateY(0);
          }
          
          /* 错误消息样式 */
          .error-message {
            background-color: rgba(254, 226, 226, 0.8);
            color: #b91c1c;
            border: 1px solid rgba(248, 113, 113, 0.5);
            padding: 0.75rem 1rem;
            border-radius: 0.5rem;
            margin-bottom: 1.5rem;
            font-size: 0.875rem;
            backdrop-filter: blur(4px);
            -webkit-backdrop-filter: blur(4px);
          }
          
          /* 新增一个客户端验证提示样式 */
          .validation-error {
            color: #e11d48;
            font-size: 0.75rem;
            margin-top: 0.375rem;
            display: none;
          }
          .invalid input {
            border-color: #e11d48;
          }
          .invalid .validation-error {
            display: block;
          }
          
          /* 返回链接样式 */
          .back-link {
            display: inline-flex;
            align-items: center;
            color: #7b5e4d;
            font-size: 0.875rem;
            margin-top: 1.5rem;
            text-decoration: none;
            transition: all 0.3s ease;
          }
          
          .back-link:hover {
            color: #6a5040;
            text-decoration: underline;
          }
          
          .back-link svg {
            margin-right: 0.375rem;
            width: 1rem;
            height: 1rem;
          }
          
          /* 装饰元素 */
          .decorative-element {
            position: absolute;
            z-index: -1;
            opacity: 0.5;
          }
          
          .decorative-element.top-right {
            top: 5%;
            right: 5%;
            width: 150px;
            height: 150px;
            background: radial-gradient(circle, rgba(123, 94, 77, 0.2) 0%, transparent 70%);
            filter: blur(40px);
          }
          
          .decorative-element.bottom-left {
            bottom: 5%;
            left: 5%;
            width: 200px;
            height: 200px;
            background: radial-gradient(circle, rgba(106, 80, 64, 0.15) 0%, transparent 70%);
            filter: blur(50px);
          }
        `}</style>
        {error && (
          <script dangerouslySetInnerHTML={{__html: `
            document.addEventListener("DOMContentLoaded", function() {
              const passwordField = document.getElementById("password");
              if (passwordField) {
                passwordField.value = "";
                passwordField.focus();
              }
            });
          `}} />
        )}
        
        {/* 添加客户端验证脚本 */}
        <script dangerouslySetInnerHTML={{__html: `
          document.addEventListener("DOMContentLoaded", function() {
            const loginForm = document.getElementById('loginForm');
            const usernameInput = document.getElementById('username');
            const passwordInput = document.getElementById('password');
            const usernameField = document.querySelector('.username-field');
            const passwordField = document.querySelector('.password-field');
            
            // 输入时清除验证错误
            usernameInput.addEventListener('input', function() {
              usernameField.classList.remove('invalid');
            });
            
            passwordInput.addEventListener('input', function() {
              passwordField.classList.remove('invalid');
            });
            
            loginForm.addEventListener('submit', function(event) {
              let isValid = true;
              
              // 验证用户名
              if (!usernameInput.value.trim()) {
                event.preventDefault();
                usernameField.classList.add('invalid');
                isValid = false;
              }
              
              // 验证密码
              if (!passwordInput.value.trim()) {
                event.preventDefault();
                passwordField.classList.add('invalid');
                isValid = false;
              }
              
              return isValid;
            });
          });
        `}} />
      </HeadComponent>

      {/* 全屏毛玻璃背景 */}
      <div class="login-bg-overlay"></div>
      
      {/* 装饰元素 */}
      <div class="decorative-element top-right"></div>
      <div class="decorative-element bottom-left"></div>

      {/* 主容器 */}
      <div class="login-container">
        <div class="login-card">
          <h1 class="login-title">管理员登录</h1>
          <p class="login-subtitle">请输入您的凭据以继续</p>
          
          {error && (
            <div class="error-message" role="alert">
              <strong>登录失败: </strong>
              <span>{error}</span>
            </div>
          )}
          
          <form method="POST" action="/api/auth/login" id="loginForm">
            <div class="form-group username-field">
              <label for="username" class="form-label">用户名</label>
              <input 
                type="text" 
                name="username" 
                id="username" 
                required 
                class="form-input"
                placeholder="请输入用户名"
                autocomplete="username"
              />
              <div class="validation-error">请输入用户名</div>
            </div>
            
            <div class="form-group password-field">
              <label for="password" class="form-label">密码</label>
              <input 
                type="password" 
                name="password" 
                id="password" 
                required 
                class="form-input"
                placeholder="请输入密码"
                autocomplete="current-password"
              />
              <div class="validation-error">请输入密码</div>
            </div>
            
            <input type="hidden" name="redirect_url" value={redirect || "/"} />
            
            <button type="submit" class="submit-button">
              登录系统
            </button>

            <p class="text-xs text-gray-400 mt-6 text-center">
              管理员账号: admin / 密码: password123
            </p>
            
          </form>
          
          <div style="text-align: center;">
            <a href="/" class="back-link">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
              </svg>
              返回首页
            </a>
          </div>

          <div class="error-message-debug hidden mt-4 p-3 rounded-lg bg-gray-50 border border-gray-200">
            <div class="text-xs font-mono whitespace-pre-wrap" id="debug-info"></div>
          </div>

          <script dangerouslySetInnerHTML={{__html: `
            document.addEventListener('DOMContentLoaded', () => {
              // 检查URL参数中是否有错误信息
              const urlParams = new URLSearchParams(window.location.search);
              const errorMessage = urlParams.get('error');
              const errorContainer = document.getElementById('error-message');
              
              if (errorMessage) {
                errorContainer.classList.remove('hidden');
                errorContainer.innerText = errorMessage;
                
                // 如果有错误，清空密码框并聚焦
                const passwordInput = document.getElementById('password');
                if (passwordInput) {
                  passwordInput.value = '';
                  passwordInput.focus();
                }
              }
              
              // 添加调试按钮
              const debugBtn = document.createElement('button');
              debugBtn.type = 'button';
              debugBtn.className = 'text-xs text-gray-400 hover:text-gray-600';
              debugBtn.innerText = '显示调试信息';
              debugBtn.style.position = 'absolute';
              debugBtn.style.bottom = '10px';
              debugBtn.style.right = '10px';
              
              debugBtn.addEventListener('click', async () => {
                const debugInfo = document.querySelector('.error-message-debug');
                const debugContent = document.getElementById('debug-info');
                
                if (debugInfo.classList.contains('hidden')) {
                  debugInfo.classList.remove('hidden');
                  try {
                    const username = document.getElementById('username').value;
                    const password = document.getElementById('password').value;
                    
                    debugContent.innerText = \`用户名: \${username}\n\`;
                    debugContent.innerText += \`密码长度: \${password.length}\n\`;
                    debugContent.innerText += \`当前时间: \${new Date().toISOString()}\n\`;
                    debugContent.innerText += \`浏览器: \${navigator.userAgent}\n\`;
                  } catch(e) {
                    debugContent.innerText = '获取调试信息出错: ' + e.message;
                  }
                } else {
                  debugInfo.classList.add('hidden');
                }
              });
              
              document.body.appendChild(debugBtn);
              
              // 表单提交前验证
              document.querySelector('form').addEventListener('submit', function(e) {
                const username = document.getElementById('username').value.trim();
                const password = document.getElementById('password').value;
                
                if (!username || !password) {
                  e.preventDefault();
                  errorContainer.classList.remove('hidden');
                  errorContainer.innerText = !username ? '请输入用户名' : '请输入密码';
                  return false;
                }
                
                // 记录提交信息到控制台
                console.log('提交表单:', { username });
                
                // 继续提交表单
                return true;
              });
            });
          `}} />
        </div>
      </div>
    </>
  );
}